document.addEventListener("DOMContentLoaded", () => {
    const $app = document.querySelector("#app");
    const zr = zrender.init($app);
    const width = 200;
    const height = 200;
    const cx = zr.getWidth() / 2;
    const cy = zr.getHeight() / 2;
    const x = cx - width / 2;
    const y = cy - height / 2;
    // 原点坐标
    const origin = [x + width / 2 , y + height / 2];
    // 是否旋转中
    let rotating = false;
    let aVector = null;
    let bVector = null;

    const shape_controls = new zrender.Rect({
        origin,
        shape: {
            x,
            y,
            width,
            height,
        },
        style: {
            fill: "transparent",
            stroke: "#000000"
        }
    });

    const shape_anchor = new zrender.Circle({
        shape: {
            r: 4,
            cx,
            cy: y
        },
        style: {
            fill: "rgb(255, 255, 255)",
            stroke: "rgb(6, 123, 239)"
        }
    });

    const shape_rotater = new zrender.Circle({
        shape: {
            r: 4,
            cx,
            cy: y - 30
        },
        style: {
            fill: "rgb(255, 255, 255)",
            stroke: "rgb(6, 123, 239)"
        }
    });

    const line = new zrender.Line({
        shape: {
            x1: cx,
            y1: y - 26,
            x2: cx,
            y2: y - 4
        },
        style: {
            fill: "transparent",
            stroke: "#000000"
        }
    });

    const group = new zrender.Group({
        origin,
    });
    group.add(shape_controls);
    group.add(shape_anchor);
    group.add(shape_rotater);
    group.add(line);

    zr.add(group);

    /**
     * 计算向量夹角，单位是弧度
     * @param {Array.<2>} av 
     * @param {Array.<2>} bv 
     * @returns {number}
     */
     function computedIncludedAngle(av, bv) {
        return Math.atan2(av[1], av[0]) - Math.atan2(bv[1], bv[0]);
    }

    shape_rotater.on("mouseover", () => {
        $app.classList.add("rotating");
    });

    shape_rotater.on("mouseout", () => {
        $app.classList.remove("rotating");
    });

    shape_rotater.on("mousedown", (e) => {
        rotating = true;
        const { offsetX, offsetY } = e;
        aVector = [offsetX - origin[0], offsetY - origin[1]];
    });

    zr.on("mousemove", (e) => {
        if (!rotating) {
            return;
        }
        $app.classList.add("rotating");
        const { offsetX, offsetY } = e;
        bVector = [offsetX - origin[0], offsetY - origin[1]];
        const angle = computedIncludedAngle(aVector, bVector);
        group.attr({
            rotation: angle
        })
        zr.flush();
    });

    zr.on("mouseup", () => {
        rotating = false;
        $app.classList.remove("rotating");
    });
});